//
//  ViewController.swift
//  BlueToothBackground
//
//  Created by macvivi on 2021/11/3.
//

import UIKit
import CoreBluetooth

class ViewController: UIViewController {
    
    
    @IBOutlet var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        tableView.dataSource = self
        tableView.delegate = self
        
        title = "搜索"
        
        weak var vc = self
        
        
        XYCentralManager.shared.startScan { (peripheral) in
//            print(peripheral.name)
//            print("当前对象地址为: \(Unmanaged<AnyObject>.passUnretained(self as! AnyObject).toOpaque())")
            
            self.tableView.reloadData()
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
//        XYCentralManager.shared.stopScan()
    }

    deinit {
        print("对象被释放了")
    }
}

extension ViewController : UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        XYCentralManager.shared.scanInfoArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let peripheral = XYCentralManager.shared.scanInfoArray[indexPath.row].peripheral
        cell.textLabel?.text = peripheral.name
        return cell
    }
    
    
}

extension ViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let peripheral:CBPeripheral = XYCentralManager.shared.scanInfoArray[indexPath.row].peripheral
        let vc = XYHelper.getViewController(storyboardStr: nil, viewController: "ContentViewController")
        XYCentralManager.shared.connect(peripheral: peripheral) { (bool, error) in
            BTBManager.shared.peripheral = peripheral
            self.navigationController?.pushViewController(vc, animated: true)

        }
    }
    
}
